<template>
  <div>
    <div class="index_headerBox">
      <div id="container">
        <div id="output"></div>
      </div>
      <index-head></index-head>
      <div class="indexCon">
        <img src="@/assets/image/logo.png"  class="index_logo">
        <div class="index_search clearfix">
          <input type="text" v-model="searchValue" @input="searchInput($event)" class="search_input"
            @keyup.enter="search_button" />
          <p class="search_button" @click="search_button">搜索一下</p>
        </div>
        <p class="index_keywords">
          <span>热词搜索：</span>
          <span v-for="item in hotWords" :key="item" @click="searchValue = item">{{item}}</span>
        </p>
      </div>
    </div>
    <com-foot></com-foot>
  </div>

</template>

<script>
  import indexHead from '../components/indexhead'
  import comFoot from '../components/comfoot'
  import Victor from './../assets/js/vector'
  import $ from 'jquery'
  import { mapGetters,mapMutations } from 'vuex'
  export default {
    data() {
      return {
        searchValue: '',
        show: false,
        hotWords: ['国内生产总值', '商品零售价格指数', '用电量'],
        ipv6: ''
      }
    },
    components: {
      comFoot,
      indexHead
    },
    created() {
      location.replace(location);

    },
    mounted() {
      $(function () {
        // 初始化 传入dom id
        var victor = new Victor("container", "output");
        var theme = [
          ["#002c4a", "#005584"],
          ["#35ac03", "#3f4303"],
          ["#ac0908", "#cd5726"],
          ["#18bbff", "#00486b"]
        ]
      });
      var ipv6 = "";
      var old_token = localStorage.getItem('TOKEN_KEY')
      if(old_token==null){
        old_token = "1"
      }
      let self = this;
      $.getJSON("https://v4v6.ipv6-test.com/json/widgetdata.php?callback=?", function(result){
        if(result.proto=="ipv6"){
          ipv6 = result.address;
        }
        console.log(ipv6)
        self.$axios.request({
          url: "5000/oauth/get/token",
          method: "post",
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
          },
          params: {
            access_token: old_token,
          }
          }).then(res => {
            let token = res.data.access_token
            if(old_token==null || old_token != token ){
              self.$axios.request({
                url: "5000/authentication/ipfree",
                method: "post",
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'client-id': 'webApp',
                    'client-secret': 'webApp',
                  },
                params: {
                  ipv6: ipv6,
                }
              })
              .then(res => {
                  let old_token = localStorage.getItem('TOKEN_KEY')
                  let token = res.data.access_token
                  if(!old_token || old_token != token){
                      localStorage.setItem('TOKEN_KEY', token)
                      // 添加登录信息埋点

                      self.$router.push('/index')
                      window.location.reload();
                  }
              }).catch((error)=>{
                if (error.response.status === 401  && error.response.data.resp_msg==="此账号已过期") {
                  self.$message({
                      message: error.response.data.resp_msg,
                      type: 'error',
                      duration: 3000,
                      onClose: function(){
                        console.log('消息框已关闭');
                      },
                      showClose: true
                  });
                  let old_token = localStorage.getItem('TOKEN_KEY')
                  
                  if(old_token!=null){
                    localStorage.clear()
                    window.location.reload(); 
                  }else{
                    localStorage.clear()
                    self.$router.push('/login')
                    window.location.reload(); 
                  }
                  
                  
                }
              }) 
            }
          }).catch((error)=>{
            self.$axios.request({
                url: "5000/authentication/ipfree",
                method: "post",
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'client-id': 'webApp',
                    'client-secret': 'webApp',
                },
                params: {
                  ipv6: ipv6,
                }
            }).then(res => {
                let old_token = localStorage.getItem('TOKEN_KEY')
                let token = res.data.access_token
                if(!old_token || old_token != token){
                    localStorage.setItem('TOKEN_KEY', token)
                    
                    self.$router.push('/index')
                    window.location.reload();
                }
            }).catch((error)=>{
                if (error.response.status === 401  && error.response.data.resp_msg==="此账号已过期") {
                  self.$message({
                      message: error.response.data.resp_msg,
                      type: 'error',
                      duration: 3000,
                      onClose: function(){
                        console.log('消息框已关闭');
                      },
                      showClose: true
                  });
                  let old_token = localStorage.getItem('TOKEN_KEY')
                  if(old_token!=null){
                    localStorage.clear()
                    window.location.reload(); 
                  }
                } 
              }) 
          })
      });
      
    },
    
    methods: {
      ...mapMutations([
        'setSearchValue'
      ]),
      setWords() {
        const arrs = ['国内生产总值', '商品零售价格指数', '用电量','居民消费者价格指数', 'PM2.5', '本科生'];
        function generateRandomArray(arrs) {
          const result = [];
          const randomCount = Math.random() < 0.5 ? 3 : 4;
          while (result.length < randomCount) {
            const randomIndex = Math.floor(Math.random() * arrs.length);
            const randomValue = arrs[randomIndex];
            if(!result.includes(randomValue)) {
              result.push(randomValue);
            }
          }
          return result;
        }
        this.hotWords = generateRandomArray(arrs)
      },
      searchInput(e) {
        var val = e.target.value;
        if (!val) return
      },
      search_button() {
        if (!this.searchValue) {
          window.location.reload()
          return
        }
        if(this.searchValue.trim() == '') return
        this.setSearchValue(this.searchValue)
        this.$router.push({ name: 'searchPage' })
      },
    },
  }
</script>



<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  #container {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: -1;
  }

  #output {
    width: 100%;
    height: 100%;
  }

</style>